<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 短信
// +----------------------------------------------------------------------
namespace app\sso\lib\sms;

use Inphp\Core\Db\Db;

class SMS
{
    //授权
    const ACT_AUTH = "auth";
    //通用
    const ACT_ALL = "all";

    /**
     * 验证是否有效
     * @param int $countryCode
     * @param int $phone
     * @param string $code
     * @param string|null $action
     * @return bool
     */
    public static function verify(int $countryCode, int $phone, string $code, ?string $action = null): bool
    {
        $action = $action ?? self::ACT_ALL;
        //检测
        $sms = Db::from("sso_sms")
            ->where("countryCode", $countryCode)
            ->where("phone", $phone)
            ->where("code", $code)
            ->where("action", $action)
            //未使用
            ->where("state", 2)
            //未过期
            ->where("expireTime", ">", date("Y-m-d H:i:s"))
            ->first();
        if (empty($sms)) {
            if ($action !== self::ACT_ALL) {
                return self::verify($countryCode, $phone, $code, self::ACT_ALL);
            }
            return false;
        }
        //每个验证码只能验证一次，将验证码使用掉
        @Db::from("sso_sms")
            ->where("id", $sms["id"])
            ->update(["state" => 1]);
        return true;
    }
}